package org.grayrabbit.pay.core.biz.manager.timer;

import java.util.List;

import org.grayrabbit.pay.core.model.entity.transaction.Trade;
import org.grayrabbit.pay.core.model.entity.transaction.TradeHistory;
import org.grayrabbit.pay.core.model.entity.transaction.TradeRecord;
import org.grayrabbit.pay.core.model.entity.transaction.TradeRecordHistory;
import org.grayrabbit.pay.core.model.enums.TradeEnum;
import org.grayrabbit.pay.core.model.utils.TradeUtil;
import org.grayrabbit.pay.core.service.transaction.TradeHistoryService;
import org.grayrabbit.pay.core.service.transaction.TradeRecordHistoryService;
import org.grayrabbit.pay.core.service.transaction.TradeRecordService;
import org.grayrabbit.pay.core.service.transaction.TradeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class CancelWaitToPayTask {

    @Autowired
    TradeService              tradeService;
    @Autowired
    TradeHistoryService       tradeHistoryService;

    @Autowired
    TradeRecordService        tradeRecordService;
    @Autowired
    TradeRecordHistoryService tradeRecordHistoryService;

    /***
     * 对状态为“待付款”的交易进行处理
     */
    @Scheduled(cron = "0 0 0 * * *")
    public void run() {
        List<Trade> waitToPayList = tradeService.findByStatus(TradeEnum.PAY_WAIT.name());
        for (Trade trade : waitToPayList) {

            trade.setTradeStatus(TradeEnum.PAY_CANCEL.name());
            tradeService.update(trade);
            TradeRecord tradeRecord = TradeUtil.fromTrade(trade);
            tradeRecordService.insert(tradeRecord);

            TradeHistory tradeHistory = new TradeHistory();
            BeanUtils.copyProperties(trade, tradeHistory);
            tradeHistoryService.insert(tradeHistory);
            TradeRecordHistory tradeRecordHistory = new TradeRecordHistory();
            BeanUtils.copyProperties(tradeRecord, tradeRecordHistory);
            tradeRecordHistory.setRecordId(null);
            tradeRecordHistoryService.insert(tradeRecordHistory);
            tradeRecordService.delete(tradeRecord);
            tradeService.delete(trade);
        }
    }

}
